package com.dai.zhenfujin.addresslist.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.ProInfoBean;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.bean.ResultBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.issue.activity.ReportActivity;
import com.dai.zhenfujin.message.ChatActivity;
import com.dai.zhenfujin.my.activity.wallet.TopUpActivity;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.CommonDialog;
import com.dai.zhenfujin.view.CustomPopWindow;
import com.dai.zhenfujin.visitingcard.app.LocationActiviy;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.adapter.EMAChatRoomManagerListener;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.adapter.EaseChatMessageList;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.model.EaseCompat;
import com.hyphenate.easeui.model.EaseDingMessageHelper;
import com.hyphenate.easeui.ui.EaseBaseFragment;
import com.hyphenate.easeui.ui.EaseChatRoomListener;
import com.hyphenate.easeui.ui.EaseGroupListener;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.utils.SPUtils;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.hyphenate.easeui.widget.EaseAlertDialog.AlertDialogUser;
import com.hyphenate.easeui.widget.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu;
import com.hyphenate.easeui.widget.EaseChatInputMenu.ChatInputMenuListener;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView;
import com.hyphenate.easeui.widget.EaseVoiceRecorderView.EaseVoiceRecorderCallback;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.PathUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * you can new an EaseChatFragment to use or you can inherit it to expand.
 * You need call setArguments to pass chatType and userId
 * <br/>
 * <br/>
 * you can see ChatActivity in demo for your reference
 */
public class EaseChatFragment extends EaseBaseFragment implements EMMessageListener, OnClickListener {
    protected static final String TAG = "EaseChatFragment";
    public static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;
    protected static final int REQUEST_CODE_DING_MSG = 4;

    protected static final int MSG_TYPING_BEGIN = 0;
    protected static final int MSG_TYPING_END = 1;

    protected static final String ACTION_TYPING_BEGIN = "TypingBegin";
    protected static final String ACTION_TYPING_END = "TypingEnd";

    protected static final int TYPING_SHOW_TIME = 5000;

    /**
     * params to fragment
     */
    protected Bundle fragmentArgs;
    protected int chatType;
    protected String toChatUsername;
    public EaseChatMessageList messageList;
    protected EaseChatInputMenu inputMenu;

    public  EMConversation conversation;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected Handler handler = new Handler();
    protected File cameraFile;
    protected EaseVoiceRecorderView voiceRecorderView;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected ListView listView;
    protected TextView textTitle,tv_fabu,tv_attention,tv_block,tv_report,tv_contact;
    protected FrameLayout fl_img,fl_alum;
    public LinearLayout ll_attention,ll_block,ll_report,ll_contact,ll_report2,ll_msg;
    protected ImageView iv_attention,iv_block,iv_report,iv_contact;

    private View kickedForOfflineLayout;

    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected GroupListener groupListener;
    protected ChatRoomListener chatRoomListener;
    public EMMessage contextMenuMessage;

    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_LOCATION = 3;

    protected int[] itemStrings = {R.string.attach_picture,R.string.attach_take_pic, R.string.attach_location};
    protected int[] itemdrawables = {R.drawable.chat_image,R.drawable.chat_takepic,
            R.drawable.chat_location};
    protected int[] itemIds = {ITEM_PICTURE,ITEM_TAKE_PICTURE, ITEM_LOCATION};
    private boolean isMessageListInited;
    protected MyItemClickListener extendMenuItemClickListener;
    protected boolean isRoaming = false;
    private ExecutorService fetchQueue;
    // to handle during-typing actions.
    private Handler typingHandler = null;
    // "正在输入"功能的开关，打开后本设备发送消息将持续发送cmd类型消息通知对方"正在输入"
    private boolean turnOnTyping;
    private PopupWindow mPopWindow;
    private boolean chatHistoryFlag;
    private CustomPopWindow customPopWindow,customPopWindow2;
    private String user_phone;
    private String user_weixin;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return inflater.inflate(R.layout.ease_fragment_chat, container, false);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, boolean roaming) {
        isRoaming = roaming;
        return inflater.inflate(R.layout.ease_fragment_chat, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        fragmentArgs = getArguments();
        // check if single chat or group chat
        chatType = fragmentArgs.getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        // userId you are chat with or group id
        toChatUsername = fragmentArgs.getString(EaseConstant.EXTRA_USER_ID);

        this.turnOnTyping = turnOnTyping();

        super.onActivityCreated(savedInstanceState);
    }

    protected boolean turnOnTyping() {
        return false;
    }

    /**
     * init view
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void initView() {
        // hold to record voice
        //noinspection ConstantConditions
        voiceRecorderView = (EaseVoiceRecorderView) getView().findViewById(R.id.voice_recorder);
        textTitle = getView().findViewById(R.id.title_textview);
        fl_img = getView().findViewById(R.id.fl_img);
        fl_alum = getView().findViewById(R.id.fl_alum);
        tv_fabu = getView().findViewById(R.id.tv_fabu);
        ll_attention = getView().findViewById(R.id.ll_attention);
        ll_block = getView().findViewById(R.id.ll_block);
        ll_report = getView().findViewById(R.id.ll_report);
       // ll_report2 = getView().findViewById(R.id.ll_report2);
        ll_contact = getView().findViewById(R.id.ll_contact); //联系方式

        tv_attention = getView().findViewById(R.id.tv_attention);
        tv_block = getView().findViewById(R.id.tv_block);
        tv_report = getView().findViewById(R.id.tv_report);

        iv_attention = getView().findViewById(R.id.iv_attention);
        iv_block = getView().findViewById(R.id.iv_block);
        iv_contact = getView().findViewById(R.id.iv_contact);
        tv_contact = getView().findViewById(R.id.tv_contact);
        iv_report = getView().findViewById(R.id.iv_report);
        ll_msg = getView().findViewById(R.id.ll_msg);

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> params2 = new HashMap<>();
        params2.put("friend_id", toChatUsername);
        params.put("req_bd", params2);
        HttpClient.post(getActivity(), Constants.QUERYFRIENDSTATE, params, new CallBack<ProInfoBean>() {
            @Override
            public void onSuccess(ProInfoBean proInfoBean) {
                user_phone = proInfoBean.user_phone;
                user_weixin = proInfoBean.user_weixin;
                if (proInfoBean.isfriend == 1){
                    tv_attention.setText("已关注");
                    iv_attention.setImageResource(R.mipmap.attention2);
                }
                if (proInfoBean.isblack == 1){
                    tv_block.setText("已拉黑");
                    iv_block.setImageResource(R.mipmap.block2);
                }
            }


        });


       /* if (null != MainActivity.followList && MainActivity.followList.size() > 0){
            for (FollowBean.FollowListBean followListBean : MainActivity.followList) {
                if (followListBean.friend_id.equals(toChatUsername)){
                    tv_attention.setText("已关注");
                    iv_attention.setBackgroundDrawable(ChatActivity.activityInstance.getDrawable(R.mipmap.attention2));
                }
            }
        }

        if (null != MainActivity.black_list && MainActivity.black_list.size() > 0) {
            for (BlackBean.FollowListBean followListBean : MainActivity.black_list) {
                if (followListBean.friend_id.equals(toChatUsername)) {
                    tv_block.setText("已拉黑");
                    iv_block.setBackgroundDrawable(ChatActivity.activityInstance.getDrawable(R.mipmap.block2));
                }
            }
        }*/

        ll_attention.setOnClickListener(this);
        ll_block.setOnClickListener(this);
        ll_report.setOnClickListener(this);
        //联系方式
        ll_contact.setOnClickListener(this);
//        ll_report2.setOnClickListener(this);

        // message list layout
        messageList = (EaseChatMessageList) getView().findViewById(R.id.message_list);
        if (chatType != EaseConstant.CHATTYPE_SINGLE)
            messageList.setShowUserNick(true);
//        messageList.setAvatarShape(1);
        listView = messageList.getListView();

        kickedForOfflineLayout = getView().findViewById(R.id.layout_alert_kicked_off);
        kickedForOfflineLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onChatRoomViewCreation();
            }
        });

        extendMenuItemClickListener = new MyItemClickListener();
        inputMenu = (EaseChatInputMenu) getView().findViewById(R.id.input_menu);
        registerExtendMenuItem();
        // init input menu
        inputMenu.init(null);

        if (SPUtils.getSendMsg(getContext(),toChatUsername)) {
            Map<String, Object> params3 = new HashMap<>();
            Map<String, Object> params4 = new HashMap<>();
            params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
            params3.put("req_bd", params4);
            HttpClient.post(getActivity(), Constants.CHATHISTORY, params3, new CallBack<ResultBean>() {
                @Override
                public void onSuccess(ResultBean resultBean) {
                    if (resultBean.state == 2) {  //已保存过
                        SPUtils.saveConversionGif(getActivity(), toChatUsername, true);
                    } else {
                        String name = com.dai.zhenfujin.utils.SPUtils.getConversionNickName(getContext(), toChatUsername);
                        //直接发送消息
                        if (!name.equals("系统消息")) {
                          //  EMMessage message = EMMessage.createTxtSendMessage("[signal]", toChatUsername);
                            sendImgMeg("[signal]");
                        }
                    }
                }
            });
        }

        inputMenu.setChatInputMenuListener(new ChatInputMenuListener() {
            @Override
            public void onTyping(CharSequence s, int start, int before, int count) {
                // send action:TypingBegin cmd msg.
                typingHandler.sendEmptyMessage(MSG_TYPING_BEGIN);
            }

            @Override
            public void onSendMessage(String content) {
                sendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderCallback() {

                    @Override
                    public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                        sendVoiceMessage(voiceFilePath, voiceTimeLength);
                    }
                });
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
            }
        });

        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);

        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        if (isRoaming) {
            fetchQueue = Executors.newSingleThreadExecutor();
        }

        // to handle during-typing actions.
        typingHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_TYPING_BEGIN: // Notify typing start

                        if (!turnOnTyping) return;

                        // Only support single-chat type conversation.
                        if (chatType != EaseConstant.CHATTYPE_SINGLE)
                            return;

                        if (hasMessages(MSG_TYPING_END)) {
                            // reset the MSG_TYPING_END handler msg.
                            removeMessages(MSG_TYPING_END);
                        } else {
                            // Send TYPING-BEGIN cmd msg
                            EMMessage beginMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                            EMCmdMessageBody body = new EMCmdMessageBody(ACTION_TYPING_BEGIN);
                            // Only deliver this cmd msg to online users
                            body.deliverOnlineOnly(true);
                            beginMsg.addBody(body);
                            beginMsg.setTo(toChatUsername);
                            EMClient.getInstance().chatManager().sendMessage(beginMsg);
                        }

                        sendEmptyMessageDelayed(MSG_TYPING_END, TYPING_SHOW_TIME);
                        break;
                    case MSG_TYPING_END:

                        if (!turnOnTyping) return;

                        // Only support single-chat type conversation.
                        if (chatType != EaseConstant.CHATTYPE_SINGLE)
                            return;

                        // remove all pedding msgs to avoid memory leak.
                        removeCallbacksAndMessages(null);
                        // Send TYPING-END cmd msg
                        EMMessage endMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                        EMCmdMessageBody body = new EMCmdMessageBody(ACTION_TYPING_END);
                        // Only deliver this cmd msg to online users
                        body.deliverOnlineOnly(true);
                        endMsg.addBody(body);
                        endMsg.setTo(toChatUsername);
                        EMClient.getInstance().chatManager().sendMessage(endMsg);
                        break;
                    default:
                        super.handleMessage(msg);
                        break;
                }
            }
        };
    }

    protected void setUpView() {
        titleBar.setTitle(toChatUsername);
        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
            // set title
            if (EaseUserUtils.getUserInfo(toChatUsername) != null) {
                EaseUser user = EaseUserUtils.getUserInfo(toChatUsername);
                if (user != null) {
                    titleBar.setTitle(user.getNickname());
                }
            }
            titleBar.setRightImageResource(R.drawable.ease_mm_title_remove);
        } else {
            titleBar.setRightImageResource(R.drawable.ease_to_group_details_normal);
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                //group chat
                EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
                if (group != null)
                    titleBar.setTitle(group.getGroupName());
                // listen the event that user moved out group or group is dismissed
                groupListener = new GroupListener();
                EMClient.getInstance().groupManager().addGroupChangeListener(groupListener);
            } else {
                chatRoomListener = new ChatRoomListener();
                EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomListener);
                onChatRoomViewCreation();
            }

        }
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }

        titleBar.setLeftLayoutClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        titleBar.setRightLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                    emptyHistory();
                } else {
                    toGroupDetails();
                }
            }
        });

        setRefreshLayoutListener();
        // show forward message if the message is not null
        String forward_msg_id = getArguments().getString("forward_msg_id");
        if (forward_msg_id != null) {
            forwardMessage(forward_msg_id);
        }
    }

    /**
     * register extend menu, item id need > 3 if you override this method and keep exist item
     */
    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], extendMenuItemClickListener);
        }
    }


    protected void onConversationInit() {
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(1), true);
        conversation.markAllMessagesAsRead();

        // the number of messages loaded into conversation is getChatOptions().getNumberOfMessagesLoaded
        // you can change this number

        if (!isRoaming) {
            //获取此会话的所有消息
            final List<EMMessage> msgs = conversation.getAllMessages();
            int msgCount = msgs != null ? msgs.size() : 0;
            if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
                String msgId = null;
                if (msgs != null && msgs.size() > 0) {
                    msgId = msgs.get(0).getMsgId();
                }
                //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
                conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
              //  if (null != conversation.getLatestMessageFromOthers().getMsgId())
                   // SPUtils.put(getActivity(),toChatUsername + "msgId",conversation.getLatestMessageFromOthers().getMsgId());
            }
        } else {
            fetchQueue.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                             EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(
                                toChatUsername, EaseCommonUtils.getConversationType(chatType), pagesize, "");
                        for (EMMessage datum : emMessageEMCursorResult.getData()) {
                            datum.setDeliverAcked(true);
                        }

                         final List<EMMessage> msgs = conversation.getAllMessages();
                        int msgCount = msgs != null ? msgs.size() : 0;
                        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
                            String msgId = null;
                            if (msgs != null && msgs.size() > 0) {
                                msgId = msgs.get(0).getMsgId();
                            }
                            //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
                            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
                        }
                        conversation.markAllMessagesAsRead();
                        messageList.refreshSelectLast();
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatType, chatFragmentHelper != null ?
                chatFragmentHelper.onSetCustomChatRowProvider() : null);
        setListItemClickListener();

        messageList.getListView().setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                inputMenu.hideExtendMenuContainer();
                return false;
            }
        });

        isMessageListInited = true;
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageList.MessageListItemClickListener() {
            @Override
            public void onUserAvatarClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarClick(username);
                }
            }

            @Override
            public boolean onResendClick(final EMMessage message) {
                EMLog.i(TAG, "onResendClick");
                new EaseAlertDialog(getContext(), R.string.resend, R.string.confirm_resend, null, new AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        message.setStatus(EMMessage.Status.CREATE);
                        sendMessage(message);
                    }
                }, true).show();
                return true;
            }

            @Override
            public void onUserAvatarLongClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarLongClick(username);
                }
            }

            @Override
            public void onBubbleLongClick(EMMessage message,View view) {
                contextMenuMessage = message;
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onMessageBubbleLongClick(message, view);
                }
            }

            @Override
            public boolean onBubbleClick(EMMessage message) {
                if (chatFragmentHelper == null) {
                    return false;
                }
                return chatFragmentHelper.onMessageBubbleClick(message);
            }

            @Override
            public void onMessageInProgress(EMMessage message) {
                message.setMessageStatusCallback(messageStatusCallback);
            }
        });
    }



    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isRoaming) {
                            //从本地获取
                            loadMoreLocalMessage();
                        } else {
                            //从内存获取
                            loadMoreRoamingMessages();
                        }
                    }
                }, 600);
            }
        });
    }

    private void loadMoreLocalMessage() {
        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
            List<EMMessage> messages;
            try {
                messages = conversation.loadMoreMsgFromDB(conversation.getAllMessages().size() == 0 ? "" : conversation.getAllMessages().get(0).getMsgId(),
                        pagesize);
            } catch (Exception e1) {
                swipeRefreshLayout.setRefreshing(false);
                return;
            }
            if (messages.size() > 0) {
                messageList.refreshSeekTo(messages.size() - 1);
                if (messages.size() != pagesize) {
                    haveMoreData = false;
                }
            } else {
                haveMoreData = false;
            }

            isloading = false;
        } else {
            Toast.makeText(getActivity(), getResources().getString(R.string.no_more_messages),
                    Toast.LENGTH_SHORT).show();
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    private void loadMoreRoamingMessages() {
        if (!haveMoreData) {
            Toast.makeText(getActivity(), getResources().getString(R.string.no_more_messages),
                    Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
            return;
        }
        if (fetchQueue != null) {
            fetchQueue.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<EMMessage> messages = conversation.getAllMessages();
                        //分页消息 从服务器获取历史消息
                        EMClient.getInstance().chatManager().fetchHistoryMessages(
                                toChatUsername, EaseCommonUtils.getConversationType(chatType), pagesize,
                                (messages != null && messages.size() > 0) ? messages.get(0).getMsgId() : "");
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    } finally {
                        Activity activity = getActivity();
                        if (activity != null) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadMoreLocalMessage();
                                }
                            });
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) { // capture new image
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
            } else if (requestCode == REQUEST_CODE_LOCAL) { // send local image
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
            } else if (requestCode == REQUEST_CODE_MAP) { // location
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                String locationAddress = data.getStringExtra("address");
                if (locationAddress != null && !locationAddress.equals("")) {
                    sendLocationMessage(latitude, longitude, locationAddress);
                } else {
                    Toast.makeText(getActivity(), R.string.unable_to_get_loaction, Toast.LENGTH_SHORT).show();
                }

            } else if (requestCode == REQUEST_CODE_DING_MSG) { // To send the ding-type msg.
                String msgContent = data.getStringExtra("msg");
                EMLog.i(TAG, "To send the ding-type msg, content: " + msgContent);
                // Send the ding-type msg.
                EMMessage dingMsg = EaseDingMessageHelper.get().createDingMessage(toChatUsername, msgContent);
                sendMessage(dingMsg);
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageList.refresh();
        EaseUI.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        EMClient.getInstance().chatManager().addMessageListener(this);

        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(this);

        // remove activity from foreground activity list
        EaseUI.getInstance().popActivity(getActivity());

        // Remove all padding actions in handler
        handler.removeCallbacksAndMessages(null);
        typingHandler.sendEmptyMessage(MSG_TYPING_END);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (groupListener != null) {
            EMClient.getInstance().groupManager().removeGroupChangeListener(groupListener);
        }

        if (chatRoomListener != null) {
            EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomListener);
        }

        if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
        }
    }

    public void onBackPressed() {
        if (inputMenu.onBackPressed()) {
            getActivity().finish();
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
                EaseAtMessageHelper.get().cleanToAtUserList();
            }
            if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
                EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
            }
        }
    }

    protected void onChatRoomViewCreation() {
        final ProgressDialog pd = ProgressDialog.show(getActivity(), "", "Joining......");
        EMClient.getInstance().chatroomManager().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(final EMChatRoom value) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity().isFinishing() || !toChatUsername.equals(value.getId()))
                            return;
                        pd.dismiss();
                        EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(toChatUsername);
                        if (room != null) {
                            titleBar.setTitle(room.getName());
                            EMLog.d(TAG, "join room success : " + room.getName());
                        } else {
                            titleBar.setTitle(toChatUsername);
                        }
                        onConversationInit();
                        onMessageListInit();

                        // Dismiss the click-to-rejoin layout.
                        kickedForOfflineLayout.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onError(final int error, String errorMsg) {
                // TODO Auto-generated method stub
                EMLog.d(TAG, "join room failure : " + error);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                    }
                });
                getActivity().finish();
            }
        });
    }

    // 接收到的消息
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        for (EMMessage message : messages) {
            String username = null;
            // group message
            if (message.getChatType() == ChatType.GroupChat || message.getChatType() == ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }

            if (!TextUtils.isEmpty(username) && username.equals("admin")){
                ll_msg.setVisibility(View.GONE);
            }else {
                ll_msg.setVisibility(View.VISIBLE);
            }
          /*  String name = message.getStringAttribute("nickname", "");
            String userPic = message.getStringAttribute("avatar", "");
            EaseUser easeUser = new EaseUser(username);
            easeUser.setAvatar(userPic);
            easeUser.setNickname(name);*/

            // if the message is for current conversation
            if (username.equals(toChatUsername) || message.getTo().equals(toChatUsername) || message.conversationId().equals(toChatUsername)) {
                messageList.refreshSelectLast();
                //已读
                conversation.markMessageAsRead(message.getMsgId());
            }
            EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
        }
    }

    /**
     * 透传消息
     * @param messages
     */
    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        for (final EMMessage msg : messages) {
            final EMCmdMessageBody body = (EMCmdMessageBody) msg.getBody();
            EMLog.i(TAG, "Receive cmd message: " + body.action() + " - " + body.isDeliverOnlineOnly());
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ACTION_TYPING_BEGIN.equals(body.action()) && msg.getFrom().equals(toChatUsername)) {
                        titleBar.setTitle(getString(R.string.alert_during_typing));
                    } else if (ACTION_TYPING_END.equals(body.action()) && msg.getFrom().equals(toChatUsername)) {
                        titleBar.setTitle(toChatUsername);
                    }
                }
            });
        }
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageRecalled(List<EMMessage> messages) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object change) {
        if (isMessageListInited) {
            messageList.refresh();
        }
    }

    //点
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_attention://关注
                Map<String, Object> params3 = new HashMap<>();
                Map<String, Object> params4 = new HashMap<>();
                params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                params3.put("req_bd", params4);

                HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                    public void onSuccess(ResultBean resultBean) {
                        if (resultBean.charging_state == 2 || resultBean.charging_state == 3){ //未扣费
                            UIUtils.showToastSafe("互相回复后才能关注哦");
                        }else  if (resultBean.charging_state == 1){
                            follow();
                        }
                    }
                });

                break;
            case R.id.ll_contact: //联系方式
               iv_contact.setImageResource(R.mipmap.contact1);
               tv_contact.setTextColor(getResources().getColor(R.color.black));
               // addBlack();
                showAddPopWindow();
                break;
            case R.id.ll_block: //
             //  iv_contact.setImageResource(R.mipmap.contact1);
             //  tv_contact.setTextColor(getResources().getColor(R.color.black));
                Map<String, Object> params = new HashMap<>();
                Map<String, Object> params2 = new HashMap<>();
                params2.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                params.put("req_bd", params2);

                HttpClient.post(getActivity(), Constants.QUERYCHARGING, params, new CallBack<ResultBean>() {
                    public void onSuccess(ResultBean resultBean) {
                        if (resultBean.charging_state == 2 || resultBean.charging_state == 3){ //未扣费
                            UIUtils.showToastSafe("互相回复后才能拉黑哦");
                        }else if (resultBean.charging_state == 1){ //已经扣除过
                            addBlack();
                        }
                    }
                });
              //  addBlack();
               // showAddPopWindow();
                break;
            case R.id.ll_report://举报
                 showReportInfo();
              //  showAddPopWindow2();
                break;
        }
       }

    private void showAddPopWindow2() {
        if (customPopWindow2 == null) {
            int popWindowWidth = (int) (UIUtils.getDeviceDensity().widthPixels / 3);
            int popWindowHeight = (int) (UIUtils.getDeviceDensity().heightPixels / 8);
            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_message_contact2, null);
            LinearLayout ll_block = contentView.findViewById(R.id.ll_block);
             tv_block = contentView.findViewById(R.id.tv_block);
             iv_block = contentView.findViewById(R.id.iv_block);
            LinearLayout ll_report = contentView.findViewById(R.id.ll_report);
            Map<String, Object> params = new HashMap<>();
            Map<String, Object> params2 = new HashMap<>();
            params2.put("friend_id", toChatUsername);
            params.put("req_bd", params2);
            HttpClient.post(getActivity(), Constants.QUERYFRIENDSTATE, params, new CallBack<ProInfoBean>() {
                @Override
                public void onSuccess(ProInfoBean proInfoBean) {
                    user_phone = proInfoBean.user_phone;
                    user_weixin = proInfoBean.user_weixin;
                    if (proInfoBean.isblack == 1){
                          tv_block.setText("已拉黑");
                          iv_block.setImageResource(R.mipmap.block2);
                    }
                }
            });

            ll_block.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, Object> params3 = new HashMap<>();
                    Map<String, Object> params4 = new HashMap<>();
                    params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                    params3.put("req_bd", params4);

                    HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                        public void onSuccess(ResultBean resultBean) {
                            if (resultBean.charging_state == 2 || resultBean.charging_state == 3){ //未扣费
                                UIUtils.showToastSafe("互相回复后才能拉黑哦");
                            }else if (resultBean.charging_state == 1){ //已经扣除过
                                addBlack();
                            }
                        }
                    });
                }
            });
            ll_report.setOnClickListener(v -> showReportInfo());
            customPopWindow2 = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(popWindowWidth, popWindowHeight)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .create();
        }
        customPopWindow2.showAsDropDown(ll_report2, 0, 0);
    }

    private void showAddPopWindow() {
        if (customPopWindow == null) {
            int popWindowWidth = (int) (UIUtils.getDeviceDensity().widthPixels / 3);
            int popWindowHeight = 250;
            View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_message_contact, null);
            LinearLayout ll_phone = contentView.findViewById(R.id.ll_phone);
            LinearLayout ll_weixin = contentView.findViewById(R.id.ll_weixin);
            ll_phone.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, Object> params3 = new HashMap<>();
                    Map<String, Object> params4 = new HashMap<>();
                    params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                    params3.put("req_bd", params4);

                    HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                        public void onSuccess(ResultBean resultBean) {
                            if (resultBean.charging_state == 2 || resultBean.charging_state == 3){ //未扣费
                                UIUtils.showToastSafe("互相回复后才能发送手机号");
                            }else  if (resultBean.charging_state == 1){
                                if (!TextUtils.isEmpty(user_phone)){
                                    sendTextMessage("我的电话:" + user_phone);
                                }else {
                                    UIUtils.showToastSafe("电话号码为空不能发送");
                                }
                            }
                        }
                    });
                }
            });
            ll_weixin.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, Object> params3 = new HashMap<>();
                    Map<String, Object> params4 = new HashMap<>();
                    params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                    params3.put("req_bd", params4);
                    HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                        public void onSuccess(ResultBean resultBean) {
                            if (resultBean.charging_state == 2 || resultBean.charging_state == 3){ //未扣费
                                UIUtils.showToastSafe("互相回复后才能发送微信");
                            }else  if (resultBean.charging_state == 1){
                                if (!TextUtils.isEmpty(user_weixin)){
                                    sendTextMessage("我的微信:" + user_weixin);
                                }else {
                                    UIUtils.showToastSafe("微信为空不能发送");
                                }
                            }
                        }
                    });
                }
            });
            customPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                    .setView(contentView)
                    .size(popWindowWidth, popWindowHeight)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .create();
        }
        customPopWindow.showAsDropDown(ll_contact, 0, 0);
    }

    /**
     * 举报
     */
    private void showReportInfo() {
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(ChatActivity.activityInstance).inflate(R.layout.popwindow_peport_info, null);
        TextView tv_tui = contentView.findViewById(R.id.tv_tui);
        TextView tv_se = contentView.findViewById(R.id.tv_se);
        TextView tv_zhenzi = contentView.findViewById(R.id.tv_zhenzi);
        TextView tv_yinsi = contentView.findViewById(R.id.tv_yinsi);
        TextView tv_gongji = contentView.findViewById(R.id.tv_gongji);
        TextView tv_qing = contentView.findViewById(R.id.tv_qing);
        TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        TextView tv_phone = contentView.findViewById(R.id.tv_phone);
        tv_phone.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                .putExtra("fb_class",tv_phone.getText().toString().trim())
                .putExtra("toChatUsername",toChatUsername)));
        tv_tui.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                     .putExtra("fb_class",tv_tui.getText().toString().trim())));
        tv_se.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                     .putExtra("fb_class",tv_se.getText().toString().trim())));
        tv_zhenzi.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                     .putExtra("fb_class",tv_zhenzi.getText().toString().trim())));
        tv_yinsi.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                     .putExtra("fb_class",tv_yinsi.getText().toString().trim())));
        tv_gongji.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                     .putExtra("fb_class",tv_gongji.getText().toString().trim())));
        tv_qing.setOnClickListener(v -> startActivity(new Intent(ChatActivity.activityInstance, ReportActivity.class)
                     .putExtra("fb_class",tv_qing.getText().toString().trim())
                      .putExtra("toChatUsername",toChatUsername)));


        tv_cancel.setOnClickListener(view -> mPopWindow.dismiss());


        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(ChatActivity.activityInstance).inflate(R.layout.activity_login, null);
        mPopWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        mPopWindow.setOnDismissListener(() -> setBackgroundAlpha(1));

    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = ChatActivity.activityInstance.getWindow().getAttributes();
        lp.alpha = v;
        ChatActivity.activityInstance.getWindow().setAttributes(lp);
    }

    private void addBlack() {
        int type2;
        if (tv_block.getText().toString().trim().equals("拉黑")) {
            type2 = 1;
        } else {
            type2 = 2;
        }
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("friend_id", toChatUsername);
        params2.put("type", type2 + "");
        params.put("req_bd", params2);
        HttpClient.post(ChatActivity.activityInstance, Constants.BLACK, params, new CallBack<ProListBean>() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onSuccess(ProListBean resultBean) throws HyphenateException {
                com.dai.zhenfujin.utils.SPUtils.saveBlackId(ChatActivity.activityInstance,toChatUsername,true);
                if (tv_block.getText().toString().equals("拉黑")) {
                    EMClient.getInstance().contactManager().addUserToBlackList(toChatUsername,true);
                    tv_block.setText("已拉黑");
                    iv_block.setImageDrawable(ChatActivity.activityInstance.getDrawable(R.mipmap.block2));
                } else {
                    tv_block.setText("拉黑");
                    EMClient.getInstance().contactManager().removeUserFromBlackList(toChatUsername);
                    iv_block.setImageDrawable(ChatActivity.activityInstance.getDrawable(R.mipmap.block));
                }
            }
        });
    }

    private void follow() {
        Map<String, Object> params3 = new HashMap<>();
        Map<String, Object> params4 = new HashMap<>();
        params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
        params3.put("req_bd", params4);

        HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                    public void onSuccess(ResultBean resultBean) {
                        if (resultBean.charging_state == 2 || resultBean.charging_state == 3){ //未扣费
                            UIUtils.showToastSafe("互相回复后才能关注哦");
                        }else {
                            int type2;
                            if (tv_attention.getText().toString().trim().equals("关注")) {
                                type2 = 1;
                            } else {
                                type2 = 2;
                            }
                            Map<String, Object> params = new HashMap<>();
                            Map<String, Object> params2 = new HashMap<>();
                            params2.put("friend_id", toChatUsername);
                            params2.put("type", type2);
                            params.put("req_bd", params2);
                            HttpClient.post(ChatActivity.activityInstance, Constants.FOLLOW, params, new CallBack<ProInfoBean>() {
                                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                                @Override
                                public void onSuccess(ProInfoBean proInfoBean) {
                                    MessageEvent messageEvent = new MessageEvent();
                                    messageEvent.setMessageKey(EventConstants.UPDATA_FOLLOW_LIST);
                                    EventBus.getDefault().post(messageEvent);
                                    if (tv_attention.getText().toString().equals("关注")) {
                                        tv_attention.setText("已关注");
                                        iv_attention.setImageResource(R.mipmap.attention2);
                                    } else {
                                        tv_attention.setText("关注");
                                        iv_attention.setImageResource(R.mipmap.attention);
                                    }

                                }
                            });
                        }
                    }
                 });
      }



    /**
     * handle the click event for extend menu
     */
    class MyItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            if (chatFragmentHelper != null) {
                if (chatFragmentHelper.onExtendMenuItemClick(itemId, view)) {
                    return;
                }
            }
            switch (itemId) {
                case ITEM_TAKE_PICTURE:
                    selectPicFromCamera();
                    break;
                case ITEM_PICTURE:
                    selectPicFromLocal();
                    break;
                case ITEM_LOCATION:
                    startActivityForResult(new Intent(getActivity(), LocationActiviy.class).putExtra("type", 1), REQUEST_CODE_MAP);

                    break;

                default:
                    break;
            }
        }

    }

    /**
     * input @
     *
     * @param username
     */
    protected void inputAtUsername(String username, boolean autoAddAtSymbol) {
        if (EMClient.getInstance().getCurrentUser().equals(username) ||
                chatType != EaseConstant.CHATTYPE_GROUP) {
            return;
        }
        EaseAtMessageHelper.get().addAtUser(username);
        EaseUser user = EaseUserUtils.getUserInfo(username);
        if (user != null) {
            username = user.getNickname();
        }
        if (autoAddAtSymbol)
            inputMenu.insertText("@" + username + " ");
        else
            inputMenu.insertText(username + " ");
    }


    /**
     * input @
     *
     * @param username
     */
    protected void inputAtUsername(String username) {
        inputAtUsername(username, true);
    }


    //send message
    protected void sendTextMessage(String content) {
        if (EaseAtMessageHelper.get().containsAtUsername(content)) {
            sendAtMessage(content);
        } else {
            EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
            sendMessage(message);
        }
    }

    /**
     * send @ message, only support group chat message
     *
     * @param content
     */
    @SuppressWarnings("ConstantConditions")
    private void sendAtMessage(String content) {
        if (chatType != EaseConstant.CHATTYPE_GROUP) {
            EMLog.e(TAG, "only support group chat message");
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
        if (EMClient.getInstance().getCurrentUser().equals(group.getOwner()) && EaseAtMessageHelper.get().containsAtAll(content)) {
            message.setAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG, EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL);
        } else {
            message.setAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG,
                    EaseAtMessageHelper.get().atListToJsonArray(EaseAtMessageHelper.get().getAtMessageUsernames(content)));
        }
        sendMessage(message);
    }


    protected void sendBigExpressionMessage(String name, String identityCode) {
        EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, name, identityCode);
        sendMessage(message);
    }

    protected void sendVoiceMessage(String filePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, toChatUsername);
        sendMessage(message);
    }

    protected void sendImageMessage(String imagePath) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, true, toChatUsername);
        sendMessage(message);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, toChatUsername);
        sendMessage(message);
    }

    protected void sendVideoMessage(String videoPath, String thumbPath, int videoLength) {
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, thumbPath, videoLength, toChatUsername);
        sendMessage(message);
    }

    protected void sendFileMessage(String filePath) {
        EMMessage message = EMMessage.createFileSendMessage(filePath, toChatUsername);
        sendMessage(message);
    }


    protected void sendMessage(EMMessage message) {
        String user_id = SPUtils.getString(ChatActivity.activityInstance,Constants.USER_MOBILE);
        if (message == null) {
            return;
        }
        if (chatFragmentHelper != null) {
            //set extension
            chatFragmentHelper.onSetMessageAttributes(message);
        }

        if (!SPUtils.getConversionUserJob2(getActivity(),toChatUsername)) { //未扣费 //扣费 true
            if (!SPUtils.getConversionGif(getActivity(),toChatUsername)){ //未发送gif图 true
                //后台保存聊天记录
                Map<String, Object> params = new HashMap<>();
                Map<String, Object> params2 = new HashMap<>();
                params2.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                params.put("req_bd", params2);
                HttpClient.post(getActivity(), Constants.CHATHISTORY, params, new CallBack<ResultBean>() {
                    @Override
                    public void onSuccess(ResultBean resultBean) {
                        if (resultBean.state == 2){ //保存过
                           // SPUtils.saveConversionGif(getActivity(), toChatUsername, true);
                            // 通过扩展属性，将userPic和userName发送出去。
                            if (message.getType().equals(EMMessage.Type.TXT)) {
                                EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                                String digest = txtBody.getMessage();
                                if (digest.contains("signal")) {
                                    return;
                                }
                            }
                            Map<String, Object> params3 = new HashMap<>();
                            Map<String, Object> params4 = new HashMap<>();
                            params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                            params3.put("req_bd", params4);
                            HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                                @Override
                                public void onSuccess(ResultBean historyBean) {
                                    if (historyBean.charging_state == 2 ){ //对方未扣费  1 是扣除过
                                        String money =  resultBean.money;
                                        String total_money =  resultBean.total_money;
                                        new CommonDialog(getActivity(), R.style.dialog, true, total_money + "!贵客来访,茶水费" + money + "元", (dialog, confirm) -> {
                                            if (confirm) {
                                                Map<String, Object> params5 = new HashMap<>();
                                                Map<String, Object> params6 = new HashMap<>();
                                                params6.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                                                params5.put("req_bd", params6);
                                                //聊天扣费接口
                                                HttpClient.post(getActivity(), Constants.CHARGING, params5, new CallBack<ResultBean>() {
                                                    @Override
                                                    public void onSuccess(ResultBean resultBean) {
                                                        if (resultBean.getErrCode() == 1 || resultBean.getErrCode() == 4) {
                                                            SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
                                                            UIUtils.showToastSafe("扣除费用成功");
                                                            sendImgMeg("[received]");

                                                        } else if (resultBean.getErrCode() == 3) {
                                                            new CommonDialog(getActivity(), R.style.dialog, false, "扣费失败，余额不足,去充值", (dialog, confirm) -> {
                                                                if (confirm) {
                                                                    startActivity(new Intent(ChatActivity.activityInstance, TopUpActivity.class));
                                                                }
                                                                dialog.dismiss();
                                                            }).show();
                                                        }else {
                                                            UIUtils.showToastSafe("被扣费未正确填写主业分类");
                                                        }
                                                    }
                                                });
                                            }
                                            dialog.dismiss();
                                        }).show();

                                    }else if (historyBean.charging_state == 1){  //已扣费或不需要扣除费用  3、非被找人不需要扣除费用
                                        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                                        String digest = txtBody.getMessage();
                                        if (digest.contains("signal")){
                                            return;
                                        }
                                        SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
                                        String userPic = SPUtils.getConversionHeadPhoto(ChatActivity.activityInstance, user_id);
                                        if (!TextUtils.isEmpty(userPic)) {
                                            message.setAttribute("avatar", userPic);
                                            Log.i("EaseChatRow----", message.getStringAttribute("avatar", ""));
                                        }
                                        String userName = SPUtils.getConversionNickName(ChatActivity.activityInstance, user_id);
                                        if (!TextUtils.isEmpty(userName)) {
                                            message.setAttribute("nickname", userName);
                                            Log.i("EaseChatRow----", message.getStringAttribute("nickname", ""));
                                        }
                                        String userJob = SPUtils.getConversionUserDuties(ChatActivity.activityInstance, user_id);
                                        if (!TextUtils.isEmpty(userName)) {
                                            message.setAttribute("position", userJob);
                                            Log.i("EaseChatRow----", message.getStringAttribute("position", ""));
                                        }

                                        // 设置自定义扩展字段
                                        message.setAttribute("em_force_notification", true);// 设置自定义扩展字段
                                        message.setMessageStatusCallback(messageStatusCallback);

                                        // Send message.
                                        EMClient.getInstance().chatManager().sendMessage(message);
                                    }else {
                                        UIUtils.showToastSafe("请耐心等待对方回复哦");
                                    }
                                }
                            });
                        }else { //保存成共 第一次
                            Map<String, Object> params3 = new HashMap<>();
                            Map<String, Object> params4 = new HashMap<>();
                            params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                            params3.put("req_bd", params4);
                            //查询聊天是否扣费
                            HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                                @Override
                                public void onSuccess(ResultBean resultBean) {
                                    if (resultBean.charging_state == 2 ){  //需要扣费
                                        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                                        String digest = txtBody.getMessage();
                                        if (digest.contains("signal")){
                                            return;
                                        }

                                        String money =  resultBean.money;
                                        String total_money =  resultBean.total_money;
                                        new CommonDialog(getActivity(), R.style.dialog, true, total_money + "!贵客来访,茶水费" + money + "元", (dialog, confirm) -> {
                                            if (confirm) {
                                                Map<String, Object> params5 = new HashMap<>();
                                                Map<String, Object> params6 = new HashMap<>();
                                                params6.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                                                params5.put("req_bd", params6);
                                                //聊天扣费接口
                                                HttpClient.post(getActivity(), Constants.CHARGING, params5, new CallBack<ResultBean>() {
                                                    @Override
                                                    public void onSuccess(ResultBean resultBean) {
                                                        if (resultBean.getErrCode() == 1 || resultBean.getErrCode() == 4) {
                                                            SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
                                                            UIUtils.showToastSafe("扣除费用成功");
                                                            sendImgMeg("[received]");

                                                        } else if (resultBean.getErrCode() == 3) {
                                                            new CommonDialog(getActivity(), R.style.dialog, false, "扣费失败，余额不足,去充值", (dialog, confirm) -> {
                                                                if (confirm) {
                                                                    startActivity(new Intent(ChatActivity.activityInstance, TopUpActivity.class));
                                                                }
                                                                dialog.dismiss();
                                                            }).show();
                                                        }else {
                                                            UIUtils.showToastSafe("被扣费未正确填写主业分类");
                                                        }
                                                    }
                                                });
                                            }
                                            dialog.dismiss();
                                        }).show();
                                    }else if (resultBean.charging_state == 1){  //不需要扣费 1是已扣过费
                                       /* if (message.getType().equals(EMMessage.Type.TXT)) {
                                            EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                                            String digest = txtBody.getMessage();
                                            if (digest.contains("signal")) {
                                                return;
                                            }
                                        }*/
                                        SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
                                        //  int count = conversation.getAllMsgCount();
                                        SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
                                        String userPic = SPUtils.getConversionHeadPhoto(ChatActivity.activityInstance, user_id);
                                        if (!TextUtils.isEmpty(userPic)) {
                                            message.setAttribute("avatar", userPic);
                                            Log.i("EaseChatRow----", message.getStringAttribute("avatar", ""));
                                        }
                                        String userName = SPUtils.getConversionNickName(ChatActivity.activityInstance, user_id);
                                        if (!TextUtils.isEmpty(userName)) {
                                            message.setAttribute("nickname", userName);
                                            Log.i("EaseChatRow----", message.getStringAttribute("nickname", ""));
                                        }
                                        String userJob = SPUtils.getConversionUserDuties(ChatActivity.activityInstance, user_id);
                                        if (!TextUtils.isEmpty(userName)) {
                                            message.setAttribute("position", userJob);
                                            Log.i("EaseChatRow----", message.getStringAttribute("position", ""));
                                        }

                                        // 设置自定义扩展字段
                                        message.setAttribute("em_force_notification", true);// 设置自定义扩展字段
                                        message.setMessageStatusCallback(messageStatusCallback);

                                        // Send message.
                                        EMClient.getInstance().chatManager().sendMessage(message);
                                    }else {  //非被找人不需要扣除费用 3
                                        sendImgMeg("[signal]");
                                    }
                                }
                            });
                        }
                    }
                });
            }else { //已发送gif
                // 通过扩展属性，将userPic和userName发送出去。
                if (message.getType().equals(EMMessage.Type.TXT)) {
                    EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                    String digest = txtBody.getMessage();
                    if (digest.contains("signal")) {
                        return;
                    }
                }
                Map<String, Object> params3 = new HashMap<>();
                Map<String, Object> params4 = new HashMap<>();
                params4.put("friend_id", UIUtils.encodeToString(toChatUsername).split("\n")[0]);
                params3.put("req_bd", params4);
                HttpClient.post(getActivity(), Constants.QUERYCHARGING, params3, new CallBack<ResultBean>() {
                    @Override
                    public void onSuccess(ResultBean historyBean) {
                        if (historyBean.charging_state == 2 || historyBean.charging_state == 3){ //对方未扣费  1 是扣除过
                            UIUtils.showToastSafe("请耐心等待对方回复哦");
                        }else if (historyBean.charging_state == 1){  //已扣费  不需要扣除费用 或已扣除
                            EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                            String digest = txtBody.getMessage();
                            if (digest.contains("signal")){
                                return;
                            }
                            SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
                            String userPic = SPUtils.getConversionHeadPhoto(ChatActivity.activityInstance, user_id);
                            if (!TextUtils.isEmpty(userPic)) {
                                message.setAttribute("avatar", userPic);
                                Log.i("EaseChatRow----", message.getStringAttribute("avatar", ""));
                            }
                            String userName = SPUtils.getConversionNickName(ChatActivity.activityInstance, user_id);
                            if (!TextUtils.isEmpty(userName)) {
                                message.setAttribute("nickname", userName);
                                Log.i("EaseChatRow----", message.getStringAttribute("nickname", ""));
                            }
                            String userJob = SPUtils.getConversionUserDuties(ChatActivity.activityInstance, user_id);
                            if (!TextUtils.isEmpty(userName)) {
                                message.setAttribute("position", userJob);
                                Log.i("EaseChatRow----", message.getStringAttribute("position", ""));
                            }

                            // 设置自定义扩展字段
                            message.setAttribute("em_force_notification", true);// 设置自定义扩展字段
                            message.setMessageStatusCallback(messageStatusCallback);

                            // Send message.
                            EMClient.getInstance().chatManager().sendMessage(message);
                        }
                    }
                });
            }
        }else {  //扣费成功
            // UIUtils.showToastSafe("扣除费用成功");
            if (message.getType().equals(EMMessage.Type.TXT)) {
                EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                String digest = txtBody.getMessage();
                if (digest.contains("signal")) {
                    return;
                }
            }
            SPUtils.saveConversionJob2(getActivity(),toChatUsername,true);
            String userPic = SPUtils.getConversionHeadPhoto(ChatActivity.activityInstance, user_id);
            if (!TextUtils.isEmpty(userPic)) {
                message.setAttribute("avatar", userPic);
                Log.i("EaseChatRow----", message.getStringAttribute("avatar", ""));
            }
            String userName = SPUtils.getConversionNickName(ChatActivity.activityInstance, user_id);
            if (!TextUtils.isEmpty(userName)) {
                message.setAttribute("nickname", userName);
                Log.i("EaseChatRow----", message.getStringAttribute("nickname", ""));
            }
            String userJob = SPUtils.getConversionUserDuties(ChatActivity.activityInstance, user_id);
            if (!TextUtils.isEmpty(userName)) {
                message.setAttribute("position", userJob);
                Log.i("EaseChatRow----", message.getStringAttribute("position", ""));
            }

            // 设置自定义扩展字段
            message.setAttribute("em_force_notification", true);// 设置自定义扩展字段
            message.setMessageStatusCallback(messageStatusCallback);

            // Send message.
            EMClient.getInstance().chatManager().sendMessage(message);
        }

        if (isMessageListInited) {
            messageList.refreshSelectLast();
        }
    }

    private void sendImgMeg(String name) {
     //   EaseEmojicon easeEmojicon =  new EaseEmojicon();
     //  easeEmojicon.setType(EaseEmojicon.Type.BIG_EXPRESSION);
     //   easeEmojicon.setIcon(R.drawable.fanpai);
     //   easeEmojicon.setName(name);
       // easeEmojicon.setIdentityCode("em");
       // EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, easeEmojicon.getName(), null);
       // EMMessage message = EMMessage.createImageSendMessage(fileName, true, toChatUsername);
        EMMessage message = EMMessage.createTxtSendMessage(name, toChatUsername);
        String user_id = SPUtils.getString(ChatActivity.activityInstance,Constants.USER_MOBILE);
        String userPic = SPUtils.getConversionHeadPhoto(ChatActivity.activityInstance, user_id);
        if (!TextUtils.isEmpty(userPic)) {
            message.setAttribute("avatar", userPic);
            Log.i("EaseChatRow----", message.getStringAttribute("avatar", ""));
        }
        String userName = SPUtils.getConversionNickName(ChatActivity.activityInstance, user_id);
        if (!TextUtils.isEmpty(userName)) {
            message.setAttribute("nickname", userName);
            Log.i("EaseChatRow----", message.getStringAttribute("nickname", ""));
        }
        String userJob = SPUtils.getConversionUserDuties(ChatActivity.activityInstance, user_id);
        if (!TextUtils.isEmpty(userName)) {
            message.setAttribute("position", userJob);
            Log.i("EaseChatRow----", message.getStringAttribute("position", ""));
        }

        message.setAttribute("em_force_notification", true);// 设置自定义扩展字段
      //  message.setAttribute("name", easeEmojicon.getName());
        message.setMessageStatusCallback(messageStatusCallback);
          SPUtils.saveConversionGif(getActivity(),toChatUsername,true);
        // Send message.
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    //===================================================================================

    protected EMCallBack messageStatusCallback = new EMCallBack() {
        @Override
        public void onSuccess() {
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onError(int code, String error) {
            Log.i("EaseChatRowPresenter", "onError: " + code + ", error: " + error);
            if (isMessageListInited) {
                messageList.refresh();
            }
        }

        @Override
        public void onProgress(int progress, String status) {
            Log.i(TAG, "onProgress: " + progress);
            if (isMessageListInited) {
                messageList.refresh();
            }
        }
    };

    /**
     * send image
     *
     * @param selectedImage
     */
    protected void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(getActivity(), R.string.cant_find_pictures, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendImageMessage(file.getAbsolutePath());
        }

    }

    /**
     * send file
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = EaseCompat.getPath(getActivity(), uri);
        EMLog.i(TAG, "sendFileByUri: " + filePath);
        if (filePath == null) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            Toast.makeText(getActivity(), R.string.File_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }
        sendFileMessage(filePath);
    }

    /**
     * capture new image
     */
    protected void selectPicFromCamera() {
        if (!EaseCommonUtils.isSdcardExist()) {
            Toast.makeText(getActivity(), R.string.sd_card_does_not_exist, Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        //noinspection ResultOfMethodCallIgnored
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, EaseCompat.getUriForFile(getContext(), cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * select local image
     */
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }


    /**
     * clear the conversation history
     */
    protected void emptyHistory() {
        String msg = getResources().getString(R.string.Whether_to_empty_all_chats);
        new EaseAlertDialog(getActivity(), null, msg, null, new AlertDialogUser() {

            @Override
            public void onResult(boolean confirmed, Bundle bundle) {
                if (confirmed) {
                    if (conversation != null) {
                        conversation.clearAllMessages();
                    }
                    messageList.refresh();
                    haveMoreData = true;
                }
            }
        }, true).show();
    }

    /**
     * open group detail
     */
    protected void toGroupDetails() {
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            if (chatFragmentHelper != null) {
                chatFragmentHelper.onEnterToChatDetails();
            }
        } else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
            if (chatFragmentHelper != null) {
                chatFragmentHelper.onEnterToChatDetails();
            }
        }
    }

    /**
     * hide
     */
    protected void hideKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * forward message
     *
     * @param forward_msg_id
     */
    protected void forwardMessage(String forward_msg_id) {
        final EMMessage forward_msg = EMClient.getInstance().chatManager().getMessage(forward_msg_id);
        EMMessage.Type type = forward_msg.getType();
        switch (type) {
            case TXT:
                if (forward_msg.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                    sendBigExpressionMessage(((EMTextMessageBody) forward_msg.getBody()).getMessage(),
                            forward_msg.getStringAttribute(EaseConstant.MESSAGE_ATTR_EXPRESSION_ID, null));
                } else {
                    // get the content and send it
                    String content = ((EMTextMessageBody) forward_msg.getBody()).getMessage();
                    sendTextMessage(content);
                }
                break;
            case IMAGE:
                // send image
                String filePath = ((EMImageMessageBody) forward_msg.getBody()).getLocalUrl();
                if (filePath != null) {
                    File file = new File(filePath);
                    if (!file.exists()) {
                        // send thumb nail if original image does not exist
                        filePath = ((EMImageMessageBody) forward_msg.getBody()).thumbnailLocalPath();
                    }
                    sendImageMessage(filePath);
                }
                break;
            default:
                break;
        }

        if (forward_msg.getChatType() == ChatType.ChatRoom) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(forward_msg.getTo());
        }
    }

    /**
     * listen the group event
     */
    class GroupListener extends EaseGroupListener {
        @Override
        public void onUserRemoved(final String groupId, String groupName) {
            getActivity().runOnUiThread(new Runnable() {

                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(getActivity(), R.string.you_are_group, Toast.LENGTH_LONG).show();
                        Activity activity = getActivity();
                        if (activity != null && !activity.isFinishing()) {
                            activity.finish();
                        }
                    }
                }
            });
        }

        @Override
        public void onGroupDestroyed(final String groupId, String groupName) {
            // prompt group is dismissed and finish this activity
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(getActivity(), R.string.the_current_group_destroyed, Toast.LENGTH_LONG).show();
                        Activity activity = getActivity();
                        if (activity != null && !activity.isFinishing()) {
                            activity.finish();
                        }
                    }
                }
            });
        }
    }

    /**
     * listen chat room event
     */
    class ChatRoomListener extends EaseChatRoomListener {

        @Override
        public void onChatRoomDestroyed(final String roomId, final String roomName) {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (roomId.equals(toChatUsername)) {
                        Toast.makeText(getActivity(), R.string.the_current_chat_room_destroyed, Toast.LENGTH_LONG).show();
                        Activity activity = getActivity();
                        if (activity != null && !activity.isFinishing()) {
                            activity.finish();
                        }
                    }
                }
            });
        }

        @Override
        public void onRemovedFromChatRoom(final int reason, final String roomId, final String roomName, final String participant) {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (roomId.equals(toChatUsername)) {
                        if (reason == EMAChatRoomManagerListener.BE_KICKED) {
                            Toast.makeText(getActivity(), R.string.quiting_the_chat_room, Toast.LENGTH_LONG).show();
                            Activity activity = getActivity();
                            if (activity != null && !activity.isFinishing()) {
                                activity.finish();
                            }
                        } else { // BE_KICKED_FOR_OFFLINE
                            // Current logged in user be kicked out by server for current user offline,
                            // show disconnect title bar, click to rejoin.
                            Toast.makeText(getActivity(), "User be kicked for offline", Toast.LENGTH_SHORT).show();
                            //连接不上环信服务器
                            kickedForOfflineLayout.setVisibility(View.VISIBLE);
                          //  SPUtils.put(ChatActivity.activityInstance,"welcome",false);
                          //  Intent intent = new Intent(ChatActivity.activityInstance, AccountPasswordActivity.class);
                          //  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                          //  ChatActivity.activityInstance.startActivity(intent);

                        }
                    }
                }
            });
        }


        @Override
        public void onMemberJoined(final String roomId, final String participant) {
            if (roomId.equals(toChatUsername)) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getActivity(), "member join:" + participant, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }

        @Override
        public void onMemberExited(final String roomId, final String roomName, final String participant) {
            if (roomId.equals(toChatUsername)) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getActivity(), "member exit:" + participant, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }


    }

    protected EaseChatFragmentHelper chatFragmentHelper;

    public void setChatFragmentHelper(EaseChatFragmentHelper chatFragmentHelper) {
        this.chatFragmentHelper = chatFragmentHelper;
    }

    public interface EaseChatFragmentHelper {
        /**
         * set message attribute
         */
        void onSetMessageAttributes(EMMessage message);

        /**
         * enter to chat detail
         */
        void onEnterToChatDetails();

        /**
         * on avatar clicked
         *
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * on avatar long pressed
         *
         * @param username
         */
        void onAvatarLongClick(String username);

        /**
         * on message bubble clicked
         */
        boolean onMessageBubbleClick(EMMessage message);

        /**
         * on message bubble long pressed
         */
        void onMessageBubbleLongClick(EMMessage message,View view);

        /**
         * on extend menu item clicked, return true if you want to override
         *
         * @param view
         * @param itemId
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);

        /**
         * on set custom chat row provider
         *
         * @return
         */
        EaseCustomChatRowProvider onSetCustomChatRowProvider();
    }

}
